const KoaRouter = require('koa-router')
const path = require('path');
const router = new KoaRouter()
const {writeFile} = require("../helper/file");
const { getData } = require('../helper/request.js')
const Methods =  require('../helper/template')
/**
 *  查询接口数据并返回为数组的格式
 **/
async function queryData(src){
    const res = await getData(src)
    const allApi = JSON.parse(res.body).paths
    const apis = []
    for(let a in allApi){
        let type = ''
        for(let t in allApi[a]){
            type = t
        }
        let api={
            url:a,
            type:type,
            description:allApi[a][type].summary,
            tag:allApi[a][type].tags
        }
        apis.push(api)
    }
    return apis
}

/**
 * 检测参数是否为/attachment/{fileIds}格式并处置
 * @param funcName
 */
function testParams(funcName, url) {
    let type = 0
    let finaName = ''
    let finaUrl = ''
    let name = funcName.match(/(?<=\{)(.+?)(?=\})/g)
    console.log(name, 'name')
    if(name) {
        // 如果是{fileIds}类型
        finaName = `params${name[0]}`
        // 修改url
        let splitUrl = url.split('/')
        finaUrl = splitUrl.slice(0, splitUrl.length - 1).join('/')
        type = 1
    } else {
        finaName = funcName
        finaUrl = url
    }
    return {
        finaName,
        type,
        finaUrl
    }
}
/**
 *  通过接口数组获取目标接口的函数
 **/
function getApiFunctions(apis){
    let apiFunctions = {}
    apis.forEach( item=>{
        const part = item.url.split('/')
        // console.log(part, 'part')
        const fileName = part[1]
        const funcName = part[part.length-1]
        // console.log(part, 'part')
        const {type,finaName,finaUrl }=testParams(funcName, item.url)
        const method = new Methods() // 函数模板
        // console.log(finaName, 'finaName')
        // console.log(finaUrl, 'finaUrl')
        const content = method[item.type](finaName,finaUrl, type)
        if(!apiFunctions[fileName]){
            apiFunctions[fileName] = [content]
        }else{
            apiFunctions[fileName].push(content)
        }
    })
    return apiFunctions
}
router.get(`/getSwigger`,   async(ctx) => {
    const {src} = ctx.request.query
    const apis = await queryData(src)
    let ul =  `<ul>`
    apis.forEach(item=>{
        ul+=`<li><strong>${item.url}</strong>---${item.description}---${item.type}</li>`
        console.log(item)
    })
    ul+=`</ul>`
    ctx.body =ul
})

router.get(`/generateFiles`,   async(ctx) => {
    const {src, module} = ctx.request.query
    const apis = await queryData(src)
    const apiFunctions = getApiFunctions(apis)
    let ul =`<ul><li>文件生成成功，查看：</li>`
    for(let i in apiFunctions){
        if(!module|| module.includes(i)) {
            const p = path.resolve('./exports/'+i+'.js')
            // const p = 'f:/2021/export/'+i+'.js'
            const funs = apiFunctions[i].join('\n')
            const res = await writeFile(p,funs)
            ul+=`<li>${res.msg}</li>`
        }
    }
    ctx.body = ul
})


router.get(`/generateApiMap`,   async(ctx) => {
    const {src} = ctx.request.query
    const apis = await queryData(src)
    let map = `export default map_config = {\n`
    apis.forEach((item,index)=>{
        const part = item.url.split('/')
        console.log(part)
        const funcName = part[part.length-1]
        let end = `,\n`
        if(index === apis.length-1){
            end = `\n`
        }
        map +=`  ${funcName}: '${item.url}'${end}`
    })
    map+='}'
    const p = path.resolve('./exports/api_map.js')
    const res = await writeFile(p,map)
    let ul =`<ul><li>文件生成成功，查看：${p}</li>`
    ctx.body = ul
})

module.exports = router

